
/**
  ******************************************************************************
  * Copyright 2021 The Microbee Authors. All Rights Reserved.
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  * http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * @file       arming_copter.c
  * @author     baiyang
  * @date       2022-11-19
  ******************************************************************************
  */

/*----------------------------------include-----------------------------------*/
#include "fms.h"
#include "logger.h"
#include "config.h"

#include <rtthread.h>

#include <mb_arming/mb_arming.h>

#include <notify/notify.h>
#include <logger/blog.h>
#include <logger/task_logger.h>

#include <ahrs/ahrs_view.h>
#include <gcs_mavlink/gcs.h>
#include <common/gp_config.h>
#include <mc_wpnav/mc_wpnav.h>
#include <mc_loiter/mc_loiter.h>
#include <common/time/gp_time.h>
#include <rc_channel/rc_channel.h>
#include <srv_channel/srv_channel.h>
#include <board_config/board_config.h>

#if CONFIG_HAL_BOARD != HAL_BOARD_SITL_WIN
#include <sensor_imu/sensor_imu.h>
#include <sensor_gps/sensor_gps.h>
#include <sensor_baro/sensor_baro.h>
#include <sensor_compass/sensor_compass.h>
#endif

#include <common/microbee.h>
/*-----------------------------------macro------------------------------------*/

/*----------------------------------typedef-----------------------------------*/

/*---------------------------------prototype----------------------------------*/
static bool arming_copter_rc_calibration_checks(bool display_failure);
static bool arming_copter_disarm(const enum ArmingMethod method, bool do_disarm_checks);
static bool arming_copter_arm(const enum ArmingMethod method, bool do_arming_checks);
static bool arming_copter_pre_arm_checks(bool display_failure);
static void arming_copter_set_pre_arm_check(bool b);
static bool arming_copter_run_pre_arm_checks(bool display_failure);
static bool arming_copter_mandatory_checks(bool display_failure);
static bool arming_copter_mandatory_gps_checks(bool display_failure);
static bool arming_copter_alt_checks(bool display_failure);
static bool arming_copter_parameter_checks(bool display_failure);
static bool arming_copter_gcs_failsafe_check(bool display_failure);
static bool arming_copter_rc_throttle_failsafe_checks(bool display_failure);
static bool arming_copter_barometer_checks(bool display_failure);
static bool arming_copter_arm_checks(enum ArmingMethod method);
static bool arming_copter_board_voltage_checks(bool display_failure);
static bool arming_copter_gps_checks(bool display_failure);
static bool arming_copter_terrain_database_required();

/*----------------------------------variable----------------------------------*/
static struct mb_arming_ops arming_ops = {.arm            = arming_copter_arm,
                                          .disarm         = arming_copter_disarm,
                                          .pre_arm_checks = arming_copter_pre_arm_checks,
                                          .arm_checks     = arming_copter_arm_checks,
                                          .barometer_checks = arming_copter_barometer_checks,
                                          .ins_checks     = NULL,
                                          .gps_checks     = arming_copter_gps_checks,
                                          .board_voltage_checks = arming_copter_board_voltage_checks,
                                          .rc_calibration_checks = arming_copter_rc_calibration_checks,
                                          .mission_checks = NULL,
                                          .terrain_database_required = arming_copter_terrain_database_required,
                                          .system_checks  = NULL,
                                          .proximity_checks = NULL,
                                          .mandatory_checks = arming_copter_mandatory_checks};

static struct mb_arming arming;
/*-------------------------------------os-------------------------------------*/

/*----------------------------------function----------------------------------*/
static bool arming_copter_rc_calibration_checks(bool display_failure)
{
    rc_channel_const_t channels[] = {
        fms.channel_roll,
        fms.channel_pitch,
        fms.channel_throttle,
        fms.channel_yaw
    };

    fms.ap.pre_arm_rc_check = mb_arming_rc_checks_copter_sub(display_failure, channels)
        & mb_arming_RcCalibrationChecks(display_failure);

    return fms.ap.pre_arm_rc_check;
}

// arming.disarm - disarm motors
static bool arming_copter_disarm(const enum ArmingMethod method, bool do_disarm_checks)
{
    // return immediately if we are already disarmed
    if (!fms.motors->_armed) {
        return true;
    }

    // do not allow disarm via mavlink if we think we are flying:
    if (do_disarm_checks &&
        method == ARMING_METHOD_MAVLINK &&
        !fms.ap.land_complete) {
        return false;
    }

    if (!mb_armingDisarm(method, do_disarm_checks)) {
        return false;
    }

#if CONFIG_HAL_BOARD == HAL_BOARD_SITL_WIN
    gcs_send_text(MAV_SEVERITY_INFO, "Disarming motors");
#endif

#if 0
    auto &ahrs = AP::ahrs();

    // save compass offsets learned by the EKF if enabled
    Compass &compass = AP::compass();
    if (ahrs.use_compass() && compass.get_learn_type() == Compass::LEARN_EKF) {
        for(uint8_t i=0; i<COMPASS_MAX_INSTANCES; i++) {
            Vector3f magOffsets;
            if (ahrs.getMagOffsets(i, magOffsets)) {
                compass.set_and_save_offsets(i, magOffsets);
            }
        }
    }

#if AUTOTUNE_ENABLED == ENABLED
    // save auto tuned parameters
    if (copter.flightmode == &copter.mode_autotune) {
        copter.mode_autotune.save_tuning_gains();
    } else {
        copter.mode_autotune.reset();
    }
#endif
#endif

    // we are not in the air
    fms_set_land_complete(true);
    fms_set_land_complete_maybe(true);

    // send disarm command to motors
    mb_motors_armed2(fms.motors,false);

#if MODE_AUTO_ENABLED == ENABLED
    // reset the mission
    mission_reset();
#endif

    // 
    fms_actuator_armed_notify(false);

    mb_arming_log_write_disarm(do_disarm_checks, method);

    if (blog_get_log_mode() == 0) {
        logger_stop_blog();
    }

    fms.ap.in_arming_delay = false;

    return true;
}

static bool arming_copter_arm(const enum ArmingMethod method, bool do_arming_checks)
{
    static bool in_arm_motors = false;

    // exit immediately if already in this function
    if (in_arm_motors) {
        return false;
    }
    in_arm_motors = true;

    // return true if already armed
    if (fms.motors->_armed) {
        in_arm_motors = false;
        return true;
    }

    if (!mb_armingArm(method, do_arming_checks)) {
        notify_events.arming_failed = true;
        in_arm_motors = false;
        return false;
    }

    // let logger know that we're armed (it may open logs e.g.)
    if (blog_get_log_mode() == 0 || 
        blog_get_log_mode() == 1) {
        logger_start_blog(NULL);
    }

    // disable cpu failsafe because initialising everything takes a while
    //copter.failsafe_disable();

    // notify that arming will occur (we do this early to give plenty of warning)
    notify_flags.armed = true;
    // call notify update a few times to ensure the message gets out
    for (uint8_t i=0; i<=10; i++) {
        notify_update();
    }

#if CONFIG_HAL_BOARD == HAL_BOARD_SITL_WIN
    gcs_send_text(MAV_SEVERITY_INFO, "Arming motors");
#endif

    // Remember Orientation
    // --------------------
    //copter.init_simple_bearing();

    fms.initial_armed_bearing = fms.ahrs->yaw_sensor_cd;

#if 0
    if (!ahrs.home_is_set()) {
        // Reset EKF altitude if home hasn't been set yet (we use EKF altitude as substitute for alt above home)
        ahrs.resetHeightDatum();
        AP::logger().Write_Event(LogEvent::EKF_ALT_RESET);

        // we have reset height, so arming height is zero
        copter.arming_altitude_m = 0;
    } else if (!ahrs.home_is_locked()) {
        // Reset home position if it has already been set before (but not locked)
        if (!copter.set_home_to_current_location(false)) {
            // ignore failure
        }

        // remember the height when we armed
        copter.arming_altitude_m = copter.inertial_nav.get_position_z_up_cm() * 0.01;
    }
    copter.update_super_simple_bearing(false);
#endif

    fms.ahrs->arming_altitude_m = ahrs_get_position_z_up_cm(fms.ahrs) * 0.01f;

    // Reset SmartRTL return location. If activated, SmartRTL will ultimately try to land at this point
#if MODE_SMARTRTL_ENABLED == ENABLED
    //copter.g2.smart_rtl.set_home(copter.position_ok());
#endif

    // enable output to motors
    mb_motors_output_min(fms.motors);

    // finally actually arm the motors
    mb_motors_armed2(fms.motors,true);

    // log flight mode in case it was changed while vehicle was disarmed
    aplog_write_mode(mode_number(fms.flightmode), fms.control_mode_reason);

    // re-enable failsafe
    //copter.failsafe_enable();

    // perf monitor ignores delay due to arming
    //AP::scheduler().perf_info.ignore_this_loop();

    // flag exiting this function
    in_arm_motors = false;

    // Log time stamp of arming event
    fms.arm_time_ms = time_millis();

    // Start the arming delay
    fms.ap.in_arming_delay = true;

    // assumed armed without a arming, switch. Overridden in switches.cpp
    //fms.ap.armed_with_airmode_switch = false;

    // 
    fms_actuator_armed_notify(true);

    mb_arming_log_write_arm(do_arming_checks, method);

    // return success
    return true;
}

static bool arming_copter_pre_arm_checks(bool display_failure)
{
    const bool passed = arming_copter_run_pre_arm_checks(display_failure);
    arming_copter_set_pre_arm_check(passed);
    return passed;
}

static void arming_copter_set_pre_arm_check(bool b)
{
    fms.ap.pre_arm_check = b;
    notify_flags.pre_arm_check = b;
}

// perform pre-arm checks
//  return true if the checks pass successfully
static bool arming_copter_run_pre_arm_checks(bool display_failure)
{
    // exit immediately if already armed
    if (fms.motors->_armed) {
        return true;
    }

    // check if motor interlock and either Emergency Stop aux switches are used
    // at the same time.  This cannot be allowed.
    if (rcs_find_channel_for_option(RC_AUX_MOTOR_INTERLOCK) &&
        (rcs_find_channel_for_option(RC_AUX_MOTOR_ESTOP) || 
        rcs_find_channel_for_option(RC_AUX_ARM_EMERGENCY_STOP))){
        mb_arming_check_failed(display_failure, "Interlock/E-Stop Conflict");
        return false;
    }

    // check if motor interlock aux switch is in use
    // if it is, switch needs to be in disabled position to arm
    // otherwise exit immediately.
    if (fms.ap.using_interlock && fms.ap.motor_interlock_switch) {
        mb_arming_check_failed(display_failure, "Motor Interlock Enabled");
        return false;
    }

    // if we are using motor Estop switch, it must not be in Estop position
    if (srv_channels_get_emergency_stop()){
        mb_arming_check_failed(display_failure, "Motor Emergency Stopped");
        return false;
    }

    if (!mb_arming_disarm_switch_checks(display_failure)) {
        return false;
    }

#if 0
    // always check motors
    char failure_msg[50] = {0};
    if (!copter.motors->arming_checks(ARRAY_SIZE(failure_msg), failure_msg)) {
        check_failed(display_failure, "Motors: %s", failure_msg);
        return false;
    }
#endif

    // if pre arm checks are disabled run only the mandatory checks
    if (arming.checks_to_perform == 0) {
        return mb_arming_mandatory_checks(display_failure);
    }

    return arming_copter_parameter_checks(display_failure)
        //& oa_checks(display_failure)
        & arming_copter_gcs_failsafe_check(display_failure)
        //& winch_checks(display_failure)
        & arming_copter_rc_throttle_failsafe_checks(display_failure)
        & arming_copter_alt_checks(display_failure)
#if AP_AIRSPEED_ENABLED
        //& AP_Arming::airspeed_checks(display_failure)
#endif
        & mb_arming_PreArmChecks(display_failure)
        ;
}

// mandatory checks that will be run if ARMING_CHECK is zero or arming forced
static bool arming_copter_mandatory_checks(bool display_failure)
{
    // call mandatory gps checks and update notify status because regular gps checks will not run
    bool result = arming_copter_mandatory_gps_checks(display_failure);
    notify_flags.pre_arm_gps_check = result;

    // call mandatory alt check
    if (!arming_copter_alt_checks(display_failure)) {
        result = false;
    }

    return result & mb_arming_MandatoryChecks(display_failure);
}

// performs mandatory gps checks.  returns true if passed
static bool arming_copter_mandatory_gps_checks(bool display_failure)
{
    // check if flight mode requires GPS
    bool mode_requires_gps = mode_requires_GPS(fms.flightmode);

#if 0
    // always check if inertial nav has started and is ready
    const auto &ahrs = AP::ahrs();
    char failure_msg[50] = {};
    if (!ahrs.pre_arm_check(mode_requires_gps, failure_msg, sizeof(failure_msg))) {
        check_failed(display_failure, "AHRS: %s", failure_msg);
        return false;
    }

    // check if fence requires GPS
    bool fence_requires_gps = false;
    #if AP_FENCE_ENABLED
    // if circular or polygon fence is enabled we need GPS
    fence_requires_gps = (copter.fence.get_enabled_fences() & (AC_FENCE_TYPE_CIRCLE | AC_FENCE_TYPE_POLYGON)) > 0;
    #endif
#endif

    // check if fence requires GPS
    bool fence_requires_gps = false;
    if (mode_requires_gps) {
        if (!fms_position_ok()) {
            // vehicle level position estimate checks
            mb_arming_check_failed(display_failure, "Need Position Estimate");
            return false;
        }
    } else {
        if (fence_requires_gps) {
            if (!fms_position_ok()) {
                // clarify to user why they need GPS in non-GPS flight mode
                mb_arming_check_failed(display_failure, "Fence enabled, need position estimate");
                return false;
            }
        } else {
            // return true if GPS is not required
            return true;
        }
    }

#if 0
    // check for GPS glitch (as reported by EKF)
    nav_filter_status filt_status;
    if (ahrs.get_filter_status(filt_status)) {
        if (filt_status.flags.gps_glitching) {
            mb_arming_check_failed(display_failure, "GPS glitching");
            return false;
        }
    }

    // check EKF's compass, position, height and velocity variances are below failsafe threshold
    if (copter.g.fs_ekf_thresh > 0.0f) {
        float vel_variance, pos_variance, hgt_variance, tas_variance;
        Vector3f mag_variance;
        ahrs.get_variances(vel_variance, pos_variance, hgt_variance, mag_variance, tas_variance);
        if (mag_variance.length() >= copter.g.fs_ekf_thresh) {
            mb_arming_check_failed(display_failure, "EKF compass variance");
            return false;
        }
        if (pos_variance >= copter.g.fs_ekf_thresh) {
            mb_arming_check_failed(display_failure, "EKF position variance");
            return false;
        }
        if (vel_variance >= copter.g.fs_ekf_thresh) {
            mb_arming_check_failed(display_failure, "EKF velocity variance");
            return false;
        }
        if (hgt_variance >= copter.g.fs_ekf_thresh) {
            mb_arming_check_failed(display_failure, "EKF height variance");
            return false;
        }
    }
#endif

    // check if home is too far from EKF origin
    Location home_loc;
    if (ahrs_get_home(get_ahrs_view(), &home_loc) && fms_far_from_EKF_origin(&home_loc)) {
        mb_arming_check_failed(display_failure, "Home too far from EKF origin");
        return false;
    }

    // check if vehicle is too far from EKF origin
    if (fms_far_from_EKF_origin(&fms.current_loc)) {
        mb_arming_check_failed(display_failure, "Vehicle too far from EKF origin");
        return false;
    }

    // if we got here all must be ok
    return true;
}

// performs altitude checks.  returns true if passed
static bool arming_copter_alt_checks(bool display_failure)
{
    // always EKF altitude estimate
    if (!mode_has_manual_throttle(fms.flightmode) && !fms_ekf_alt_ok()) {
        mb_arming_check_failed(display_failure, "Need Alt Estimate");
        return false;
    }

    return true;
}

static bool arming_copter_parameter_checks(bool display_failure)
{
    // check various parameter values
    if ((arming.checks_to_perform == ARMING_CHECK_ALL) || (arming.checks_to_perform & ARMING_CHECK_PARAMETERS)) {

        // failsafe parameter checks
        if (fms.g.failsafe_throttle) {
            // check throttle min is above throttle failsafe trigger and that the trigger is above ppm encoder's loss-of-signal value of 900
            if (rc_get_radio_min(fms.channel_throttle) <= fms.g.failsafe_throttle_value+10 || fms.g.failsafe_throttle_value < 910) {
                mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, "Check FS_THR_VALUE");
                return false;
            }
        }
        if (fms.g.failsafe_gcs == FS_GCS_ENABLED_CONTINUE_MISSION) {
            // FS_GCS_ENABLE == 2 has been removed
            mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, "FS_GCS_ENABLE=2 removed, see FS_OPTIONS");
        }

        // lean angle parameter check
        if (fms.g.angle_max < 1000 || fms.g.angle_max > 8000) {
            mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, "Check ANGLE_MAX");
            return false;
        }

#if 0
        // acro balance parameter check
#if MODE_ACRO_ENABLED == ENABLED || MODE_SPORT_ENABLED == ENABLED
        if ((copter.g.acro_balance_roll > copter.attitude_control->get_angle_roll_p().kP()) || (copter.g.acro_balance_pitch > copter.attitude_control->get_angle_pitch_p().kP())) {
            check_failed(ARMING_CHECK_PARAMETERS, display_failure, "Check ACRO_BAL_ROLL/PITCH");
            return false;
        }
#endif
#endif

        // pilot-speed-up parameter check
        if (fms.g.pilot_speed_up <= 0) {
            mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, "Check PILOT_SPEED_UP");
            return false;
        }

#if 0
        #if FRAME_CONFIG == HELI_FRAME
        if (copter.g2.frame_class.get() != AP_Motors::MOTOR_FRAME_HELI_QUAD &&
            copter.g2.frame_class.get() != AP_Motors::MOTOR_FRAME_HELI_DUAL &&
            copter.g2.frame_class.get() != AP_Motors::MOTOR_FRAME_HELI) {
            check_failed(ARMING_CHECK_PARAMETERS, display_failure, "Invalid Heli FRAME_CLASS");
            return false;
        }

        // check helicopter parameters
        if (!copter.motors->parameter_check(display_failure)) {
            check_failed(ARMING_CHECK_PARAMETERS, display_failure, "Heli motors checks failed");
            return false;
        }

        char fail_msg[50];
        // check input manager parameters
        if (!copter.input_manager.parameter_check(fail_msg, ARRAY_SIZE(fail_msg))) {
            check_failed(ARMING_CHECK_PARAMETERS, display_failure, "%s", fail_msg);
            return false;
        }

        // Inverted flight feature disabled for Heli Single and Dual frames
        if (copter.g2.frame_class.get() != AP_Motors::MOTOR_FRAME_HELI_QUAD &&
            rc().find_channel_for_option(RC_Channel::aux_func_t::INVERTED) != nullptr) {
            check_failed(ARMING_CHECK_PARAMETERS, display_failure, "Inverted flight option not supported");
            return false;
        }
        // Ensure an Aux Channel is configured for motor interlock
        if (rc().find_channel_for_option(RC_Channel::aux_func_t::MOTOR_INTERLOCK) == nullptr) {
            check_failed(ARMING_CHECK_PARAMETERS, display_failure, "Motor Interlock not configured");
            return false;
        }

        #else
        if (copter.g2.frame_class.get() == AP_Motors::MOTOR_FRAME_HELI_QUAD ||
            copter.g2.frame_class.get() == AP_Motors::MOTOR_FRAME_HELI_DUAL ||
            copter.g2.frame_class.get() == AP_Motors::MOTOR_FRAME_HELI) {
            check_failed(ARMING_CHECK_PARAMETERS, display_failure, "Invalid MultiCopter FRAME_CLASS");
            return false;
        }
        #endif // HELI_FRAME

        // checks when using range finder for RTL
#if MODE_RTL_ENABLED == ENABLED
        if (mrtl_get_alt_type() == RTL_ALTTYPE_TERRAIN) {
            // get terrain source from wpnav
            const char *failure_template = "RTL_ALT_TYPE is above-terrain but %s";
            switch (wpnav_get_terrain_source(fms.wp_nav)) {
            case WPNAV_TERRAIN_UNAVAILABLE:
                mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, failure_template, "no terrain data");
                return false;
                break;
            case WPNAV_TERRAIN_FROM_RANGEFINDER:
                if (!fms.rangefinder_state.enabled || !fms.rangefinder.has_orientation(ROTATION_PITCH_270)) {
                    mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, failure_template, "no rangefinder");
                    return false;
                }
                // check if RTL_ALT is higher than rangefinder's max range
                if (fms.g.rtl_altitude > fms.rangefinder.max_distance_cm_orient(ROTATION_PITCH_270)) {
                    mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, failure_template, "RTL_ALT>RNGFND_MAX_CM");
                    return false;
                }
                break;
            case WPNAV_TERRAIN_FROM_TERRAINDATABASE:
                // these checks are done in AP_Arming
                break;
            }
        }
#endif


        // check adsb avoidance failsafe
#if HAL_ADSB_ENABLED
        if (fms.failsafe.adsb) {
            mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, "ADSB threat detected");
            return false;
        }
#endif

        // ensure controllers are OK with us arming:
        char failure_msg[50] = {};
        if (!copter.pos_control->pre_arm_checks("PSC", failure_msg, ARRAY_SIZE(failure_msg))) {
            mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, "Bad parameter: %s", failure_msg);
            return false;
        }
        if (!copter.attitude_control->pre_arm_checks("ATC", failure_msg, ARRAY_SIZE(failure_msg))) {
            mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, display_failure, "Bad parameter: %s", failure_msg);
            return false;
        }
#endif

    }

    return true;
}

// Check GCS failsafe
static bool arming_copter_gcs_failsafe_check(bool display_failure)
{
    if (fms.failsafe.gcs) {
        mb_arming_check_failed(display_failure, "GCS failsafe on");
        return false;
    }
    return true;
}

static bool arming_copter_rc_throttle_failsafe_checks(bool display_failure)
{
    if ((arming.checks_to_perform != ARMING_CHECK_ALL) &&
        (arming.checks_to_perform & ARMING_CHECK_RC) == 0) {
        // this check has been disabled
        return true;
    }

    // throttle failsafe.  In this case the parameter also gates the
    // no-pulses RC failure case - the radio-in value can be zero due
    // to not having received any RC pulses at all.  Note that if we
    // have ever seen RC and then we *lose* RC then these checks are
    // likely to pass if the user is relying on no-pulses to detect RC
    // failure.  However, arming is precluded in that case by being in
    // RC failsafe.
    if (fms.g.failsafe_throttle == FS_THR_DISABLED) {
        return true;
    }

#if FRAME_CONFIG == HELI_FRAME
    const char *rc_item = "Collective";
#else
    const char *rc_item = "Throttle";
#endif

    if (!rcs_has_had_rc_receiver() && !rcs_has_had_rc_override()) {
        mb_arming_check_failed2(ARMING_CHECK_RC, display_failure, "RC not found");
        return false;
    }

    // check throttle is not too low - must be above failsafe throttle
    if (rc_get_radio_in(fms.channel_throttle) < fms.g.failsafe_throttle_value) {
        mb_arming_check_failed2(ARMING_CHECK_RC, display_failure, "%s below failsafe", rc_item);
        return false;
    }

    return true;
}

static bool arming_copter_barometer_checks(bool display_failure)
{
    if (!mb_arming_BarometerChecks(display_failure)) {
        return false;
    }

    bool ret = true;

#if 0
    // check Baro
    if ((checks_to_perform == ARMING_CHECK_ALL) || (checks_to_perform & ARMING_CHECK_BARO)) {
        // Check baro & inav alt are within 1m if EKF is operating in an absolute position mode.
        // Do not check if intending to operate in a ground relative height mode as EKF will output a ground relative height
        // that may differ from the baro height due to baro drift.
        nav_filter_status filt_status = copter.inertial_nav.get_filter_status();
        bool using_baro_ref = (!filt_status.flags.pred_horiz_pos_rel && filt_status.flags.pred_horiz_pos_abs);
        if (using_baro_ref) {
            if (fabsf(copter.inertial_nav.get_position_z_up_cm() - copter.baro_alt) > PREARM_MAX_ALT_DISPARITY_CM) {
                check_failed(ARMING_CHECK_BARO, display_failure, "Altitude disparity");
                ret = false;
            }
        }
    }
#endif

    return ret;
}

// arm_checks - perform final checks before arming
//  always called just before arming.  Return true if ok to arm
//  has side-effect that logging is started
static bool arming_copter_arm_checks(enum ArmingMethod method)
{
#if 0
    // always check if inertial nav has started and is ready
    if (!ahrs.healthy()) {
        check_failed(true, "AHRS not healthy");
        return false;
    }

#ifndef ALLOW_ARM_NO_COMPASS
    // if non-compass is source of heading we can skip compass health check
    if (!ahrs.using_noncompass_for_yaw()) {
        // check compass health
        if (!sensor_compass_healthy()) {
            mb_arming_check_failed(true, "Compass not healthy");
            return false;
        }
    }
#endif
#endif

    // always check if the current mode allows arming
    if (!mode_allows_arming(fms.flightmode, method)) {
        mb_arming_check_failed(true, "%s mode not armable", mode_name(fms.flightmode));
        return false;
    }

    // succeed if arming checks are disabled
    if (arming.checks_to_perform == 0) {
        return true;
    }

    // check lean angle
    if ((arming.checks_to_perform == ARMING_CHECK_ALL) || (arming.checks_to_perform & ARMING_CHECK_INS)) {
        if (degrees(acosf(fms.ahrs->cos_roll*fms.ahrs->cos_pitch))*100.0f > fms.g.angle_max) {
            mb_arming_check_failed2(ARMING_CHECK_INS, true, "Leaning");
            return false;
        }
    }

#if 0
    // check adsb
#if HAL_ADSB_ENABLED
    if ((checks_to_perform == ARMING_CHECK_ALL) || (checks_to_perform & ARMING_CHECK_PARAMETERS)) {
        if (copter.failsafe.adsb) {
            mb_arming_check_failed2(ARMING_CHECK_PARAMETERS, true, "ADSB threat detected");
            return false;
        }
    }
#endif
#endif

    // check throttle
    if ((arming.checks_to_perform == ARMING_CHECK_ALL) || (arming.checks_to_perform & ARMING_CHECK_RC)) {
         #if FRAME_CONFIG == HELI_FRAME
        const char *rc_item = "Collective";
        #else
        const char *rc_item = "Throttle";
        #endif
        // check throttle is not too high - skips checks if arming from GCS in Guided
        if (!(method == ARMING_METHOD_MAVLINK && (mode_number(fms.flightmode) == GUIDED || mode_number(fms.flightmode) == GUIDED_NOGPS || mode_number(fms.flightmode) == AUTO))) {
            // above top of deadband is too always high
            if (fms_get_pilot_desired_climb_rate(rc_get_control_in(fms.channel_throttle)) > 0.0f) {
                mb_arming_check_failed2(ARMING_CHECK_RC, true, "%s too high", rc_item);
                return false;
            }
            // in manual modes throttle must be at zero
            #if FRAME_CONFIG != HELI_FRAME
            if ((mode_has_manual_throttle(fms.flightmode) || mode_number(fms.flightmode) == DRIFT) && rc_get_control_in(fms.channel_throttle) > 0) {
                mb_arming_check_failed2(ARMING_CHECK_RC, true, "%s too high", rc_item);
                return false;
            }
            #endif
        }
    }

    // check if safety switch has been pushed
    if (brd_safety_switch_state() == SAFETY_DISARMED) {
        mb_arming_check_failed(true, "Safety Switch");
        return false;
    }

    // superclass method should always be the last thing called; it
    // has side-effects which would need to be cleaned up if one of
    // our arm checks failed
    return mb_arming_ArmChecks(method);
}

static bool arming_copter_board_voltage_checks(bool display_failure)
{
    if (!mb_arming_BoardVoltageChecks(display_failure)) {
        return false;
    }

    // check battery voltage
    if ((arming.checks_to_perform == ARMING_CHECK_ALL) || (arming.checks_to_perform & ARMING_CHECK_VOLTAGE)) {
        if (battmonitor_has_failsafed()) {
            mb_arming_check_failed2(ARMING_CHECK_VOLTAGE, display_failure, "Battery failsafe");
            return false;
        }
    }

    return true;
}

static bool arming_copter_gps_checks(bool display_failure)
{
    // check if fence requires GPS
    bool fence_requires_gps = false;

#if 0
    #if AP_FENCE_ENABLED
    // if circular or polygon fence is enabled we need GPS
    fence_requires_gps = (copter.fence.get_enabled_fences() & (AC_FENCE_TYPE_CIRCLE | AC_FENCE_TYPE_POLYGON)) > 0;
    #endif
#endif

    // check if flight mode requires GPS
    //bool mode_requires_gps = mode_requires_GPS(fms.flightmode) || fence_requires_gps || (copter.simple_mode == Copter::SimpleMode::SUPERSIMPLE);
    bool mode_requires_gps = mode_requires_GPS(fms.flightmode) || fence_requires_gps;

    // call parent gps checks
    if (mode_requires_gps) {
        if (!mb_arming_GpsChecks(display_failure)) {
            notify_flags.pre_arm_gps_check = false;
            return false;
        }
    }

    // run mandatory gps checks first
    if (!arming_copter_mandatory_gps_checks(display_failure)) {
        notify_flags.pre_arm_gps_check = false;
        return false;
    }

    // return true if GPS is not required
    if (!mode_requires_gps) {
        notify_flags.pre_arm_gps_check = true;
        return true;
    }

    // return true immediately if gps check is disabled
    if (!(arming.checks_to_perform == ARMING_CHECK_ALL || arming.checks_to_perform & ARMING_CHECK_GPS)) {
        notify_flags.pre_arm_gps_check = true;
        return true;
    }

#if CONFIG_HAL_BOARD == HAL_BOARD_RTTHREAD
    // warn about hdop separately - to prevent user confusion with no gps lock
    if (sensor_gps_get_hdop() > fms.g.gps_hdop_good) {
        mb_arming_check_failed2(ARMING_CHECK_GPS, display_failure, "High GPS HDOP");
        notify_flags.pre_arm_gps_check = false;
        return false;
    }
#endif

    // if we got here all must be ok
    notify_flags.pre_arm_gps_check = true;
    return true;
}

// expected to return true if the terrain database is required to have
// all data loaded
static bool arming_copter_terrain_database_required()
{
    if (wpnav_get_terrain_source(fms.wp_nav) == WPNAV_TERRAIN_FROM_TERRAINDATABASE &&
        mrtl_get_alt_type() == RTL_ALTTYPE_TERRAIN) {
        return true;
    }

    return mb_arming_TerrainDatabaseRequired();
}

// 
static int arming_copter_ctor(void)
{
    mb_arming_ctor(&arming, &arming_ops);

    return 0;
}
MB_INIT_COMPONENT_EXPORT(arming_copter_ctor);
/*------------------------------------test------------------------------------*/


